/**
 * Created by Administrator on 2015/4/29.
 * 系统支持功能
 */
var express = require('express');
var router = express.Router();
//文件上传类
var formidable = require('formidable'),
    util = require('util'),fs=require('fs');

//时间格式化
var moment = require('moment');
var gm = require('gm');
var url = require('url');
var mime = require('../util/mime').types;
var system = require('../util/system');

//栏目对象
var Column = require('../models/column');
var Content = require('../models/content');
var ContentList = require('../models/contentList');


var mongoose = require('mongoose');

var db = mongoose.connect('mongodb://localhost:27017/cxy');

/* GET users listing. */
router.post('/upload', function(req, res, next) {
//    获取传入参数
    var params = url.parse(req.url,true);
    var fileType;
    var fileKey = params.query.key;
    var form = new formidable.IncomingForm(),files=[],fields=[],docs=[];
    console.log('start upload');

    //存放目录
    var updatePath = "public/upload/images/";
    var smallImgPath = "public/upload/smallimgs/";
    var newFileName = "";
    form.uploadDir = updatePath;
    console.log(req.body);

    form.on('field', function(field, value) {
        fields.push([field, value]);
    }).on('file', function(field, file) {
        files.push([field, file]);
        docs.push(file);
        fileType=file.type.split('/')[0];
        //校验文件的合法性
        var realFileType = system.getFileMimeType(file.path);
        var contentType  = mime[realFileType.fileType] || 'unknown';
        if(contentType == 'unknown'){
            res.end('typeError');
        }
        var typeKey = "others";
        var thisType = file.name.split('.')[1];
        var date = new Date();
        var ms = moment(date).format('MMDDHHmmss').toString();
        if(fileType == 'image'){
            typeKey = "img";
        }
        console.log(file);
        newFileName = typeKey+ms+'.'+thisType;

        if(fileType == 'image'){
            if(realFileType.fileType == 'jpg' || realFileType.fileType == 'jpeg' || realFileType.fileType == 'png'  || realFileType.fileType == 'gif'){
                    fs.rename(file.path,updatePath + newFileName,function(err){
                        if(err){
                            console.log(err)
                        }else{
                            // 图片缩放
                            var input =  updatePath + newFileName;
                            var out = smallImgPath + newFileName;

                            if(fileKey == 'ctTopImg'){
                                gm(input).resize(270,162,'!').autoOrient().write(out, function (err) {
                                    if (err) {
                                        console.log(err);
                                    } else {
                                        console.log('done');
                                    }
                                });
                            }else if(fileKey == 'plugTopImg'){ // 插件主题图片
                                gm(input).resize(270,162,'!').autoOrient().write(out, function (err) {
                                    if (err) {
                                        console.log(err);
                                    } else {
                                        console.log('done');
                                    }
                                });
                            }else if(fileKey == 'userlogo'){ // 用户头像
                                gm(input).resize(100,100,'!').autoOrient().write(out, function (err) {
                                    if (err) {
                                        console.log(err);
                                    } else {
                                        console.log('done');
                                    }
                                });
                            }
                        }
                    })
            }else{
                res.end('typeError');
            }

        }

    }).on('end', function() {

        // 返回文件路径
        if((fileKey == 'ctTopImg' || fileKey == 'plugTopImg' || fileKey == 'userlogo')){
            console.log('/upload/images/'+newFileName);
            res.json({location:'/upload/images/'+newFileName});
        }else{
            console.log('/upload/images/'+newFileName);
            res.json({location:'/upload/images/'+newFileName});
        }

    });

    form.parse(req, function(err, fields, files) {
        err && console.log('formidabel error : ' + err);
        console.log('parsing done');
    });
});
router.post('/content',function(req,res,next){
    console.log(req.body);
    Content.findOne({url:req.body.url}, function (error, result) {
        if(error){
            res.json({err:error})
        }
        if(result==null){
            var addContent=new Content(req.body);
            addContent.save(function (error, result) {
                if(error){
                   console.log(error) ;
                }else{
                    var addContentList=new ContentList(req.body);
                    addContentList.save(function(error,result){
                            if(error){
                                res.json({err:error});
                            }else{
                                console.log("成功") ;
                                res.json({status:1})
                            }
                        });
                }
            });
        }else{
            Content.update({url:req.body.url},req.body, function (error,result) {
                if(error){
                    res.json({err:error})
                }else{
                    ContentList.update({url:req.body.url},req.body, function (error, result) {
                        console.log(result);
                        if(error) {
                            res.json({err: error})
                        }else{
                            res.json({status:2})
                        }
                    })
                }
            })

        }
    })


});
router.get('/contentlist', function (req,res,next) {
    if(req.query.page&&req.query.limit){
        var page=parseInt(req.query.page);
        var pageSize=parseInt(req.query.limit);
        ContentList.find({},{name:1,url:1,date:1,sortDate:1,author:1}, {sort:{sortDate:-1},skip:(page-1)*pageSize,limit:pageSize},function (err, result) {
            if(err){
                console.log(err);
            }
            res.json(result)
        })
    }else if(req.query.count){
        ContentList.count({}, function (error, result) {
            res.json({count:result})
        })
    }else if(req.query.updatetime&&req.query.url){
        console.log(req.query.updatetime);
        console.log(req.query.url);
        ContentList.findOne({url:req.query.url}, function (error,result) {
            if(error){
                res.json({err:error})
            }else{
                if(result == null){
                    res.json({status:0})
                }else{
                    ContentList.findOneAndUpdate({url:req.query.url},{sortDate:req.query.updatetime}, function (error, result) {
                        if (error) {
                            res.json({err: error})
                        } else {
                            res.json({status: 1})
                        }

                })
        }
            }

        })
    }

});
router.post('/column',function(req,res,next){
    Column.findOne({columnid:req.body.columnid}, function (err, result) {
        console.log(result);
       if(result ==null){
           var addColumn=new Column(req.body);
           addColumn.save();
           res.json({status:1})
       }else{
           res.json({status:0})
       }
    });
});
router.get('/column',function(req,res,next){
    Column.find({}, function (err, result) {
           res.json(result)
    });
});
router.get('/editcontent',function(req,res,next){
    if(req.query.url){
        Content.findOne({url:req.query.url},function(error,result){
            if(error){
                res.json({err:error})
            }else{
                res.json(result);
            }
        })
    }
});



module.exports = router;